package com.kb.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Configuration {

	private static Configuration instance = null;
	private Map<String, String> propsMap = new HashMap<String, String>();
	private String dbUrl;
	private String dbDriver;
	private String dbUser;
	private String dbPwd;
	
	public String getDbUrl() {
		return dbUrl;
	}
	public String getDbDriver() {
		return dbDriver;
	}
	public String getDbUser() {
		return dbUser;
	}
	public String getDbPwd() {
		return dbPwd;
	}
	
	private Configuration() {
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		File f = new File(cl.getResource("").getPath());
		try {
			String conf = f.getAbsolutePath()
					+ System.getProperties().getProperty("file.separator")
					+ Constants.DB_CONFIG_FILE_NAME;
			this.loadConfig(conf.replaceAll("%20", " "));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void loadConfig(String conf) throws IOException {

		InputStream in = new BufferedInputStream(new FileInputStream(conf));
		Properties properties = new Properties();
		properties.load(in);

		Enumeration<?> en = properties.propertyNames();
		while (en.hasMoreElements()) {
			String key = (String) en.nextElement();
			this.propsMap.put(key, properties.getProperty(key));
		}

		this.dbDriver = properties.getProperty(Constants.DB_DRIVER );
		this.dbUrl = properties.getProperty(Constants.DB_URL );
		this.dbUser = properties.getProperty(Constants.DB_USER );
		this.dbPwd = properties.getProperty(Constants.DB_PWD );
	}
	
	public Map<String, String> getPropsMap() {
		return propsMap;
	}

	public synchronized static Configuration getInstance() {
		if (instance == null) {
			instance = new Configuration();
		}
		return instance;
	}
}
